import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: [
      {
        name: '手机',
        price: 1000,
        description: '最新款智能手机',
        quantity: 0
      },
      {
        name: '电脑',
        price: 2000,
        description: '高性能笔记本电脑',
        quantity: 1
      },
      {
        name: '键盘',
        price: 200,
        description: '机械键盘',
        quantity: 0
      }
    ]
  },
  mutations: {
    incrementQuantity(state, item) {
      const product = state.cart.find(p => p.name === item)
      if (product) {
        Vue.set(product, 'quantity', product.quantity + 1)
      }
    },
    decrementQuantity(state, item) {
      const product = state.cart.find(p => p.name === item)
      if (product && product.quantity > 0) {
        Vue.set(product, 'quantity', product.quantity - 1)
      }
      // 如果数量为0，从购物车中移除该商品
      if (product && product.quantity === 0) {
        state.cart.splice(state.cart.indexOf(product), 1)
      }
    },
    addProductToCart(state, product) {
      const existingProduct = state.cart.find(p => p.name === product.name)
      if (!existingProduct) {
        state.cart.push({
          ...product,
          quantity: 1
        })
      } else {
        Vue.set(existingProduct, 'quantity', existingProduct.quantity + 1)
      }
    }
  },
  getters: {
    totalPrice: (state) => {
      return state.cart.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    }
  }
}) 